import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: () => ({
    token: getToken() || null,
    userInfo: {}
  }),
  mutations: {
    // 设置token
    setToken(state, value) {
      state.token = value
      setToken(value)
    },
    // 删除缓存
    removeToken(state) {
      state.token = null
      state.userInfo = {}
      removeToken()
      resetRouter()
    },
    // 设置用户信息
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    asyncSetToken(store, data) {
      return new Promise((resolve, reject) => {
        // 手机号和密码
        login(data).then(res => {
          // 调用mutations方法
          store.commit('setToken', res)
          resolve(res)
        })
      })
    },
    // 获取用户资料action
    async asyncGetUserInfo(ctx) {
      // 用户信息
      const res = await getUserInfo()
      // 用户头像
      const imgInfo = await getUserDetailById(res.userId)
      ctx.commit('setUserInfo', { ...res, ...imgInfo })
      return res.roles.menus
    }
  }
}
